/********************************************
 * 功能说明: Web端Role基础业务控制器
 * 模块名称:
 * 系统名称:
 * 软件版权: Frank
 * 系统版本: 1.0.0.1
 * 开发人员:
 * 开发时间: 2019-12-18 18:41:08
 * 审核人员:
 * 相关文档:
 * 修改记录: 修改日期 修改人员 修改说明
 *********************************************/
package com.spring.arch.uaa.web.controller;

import com.codahale.metrics.annotation.Timed;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import com.spring.arch.common.dto.result.PageResultDTO;
import com.spring.arch.common.dto.result.ResultDTO;
import com.spring.arch.common.security.CurrentUserContextHolder;
import com.spring.arch.common.security.UserPrincipal;
import com.spring.arch.uaa.enums.ControlRange;
import com.spring.arch.uaa.errorcode.UaaErrorCode;
import com.spring.arch.uaa.web.converter.WebRoleConverter;
import com.spring.arch.uaa.web.dto.WebRoleDTO;
import com.spring.arch.common.dto.result.PageResultDTO;
import com.spring.arch.common.dto.result.ResultDTO;
import com.spring.arch.common.exception.ExceptionHolder;
import com.spring.arch.common.exception.GlobalErrorCode;
import com.spring.arch.common.security.CurrentUserContextHolder;
import com.spring.arch.common.security.UserPrincipal;
import com.spring.arch.uaa.enums.ControlRange;
import com.spring.arch.uaa.model.QRole;
import com.spring.arch.uaa.model.Role;
import com.spring.arch.uaa.repository.RoleRepository;
import com.spring.arch.uaa.service.RoleService;
import com.spring.arch.uaa.web.converter.WebRoleConverter;
import com.spring.arch.uaa.web.dto.WebRoleDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.querydsl.binding.QuerydslPredicate;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.UUID;

import static com.spring.arch.uaa.errorcode.UaaErrorCode.E2001005002;


/**
 * Web端Role基础业务控制器
 * @author Frank
 * @version 1.0.0.1
 * @since 2019-12-18 18:41:08
 */
@Slf4j
@RestController
@RequestMapping(value = "/uaa/w/role", produces = MediaType.APPLICATION_JSON_VALUE)
@Api(tags = {"Web端Role管理API" })
public class WebRoleController {

    @Autowired
    private RoleService roleService;
    @Autowired
    private RoleRepository roleRepository;
    @Autowired
    private WebRoleConverter roleConverter;

    /**
     * 新建操作
     *
     * @param roleDTO 新建资源的DTO
     * @return 新建资源
     */
    @Timed
    @ApiOperation(value = "新建操作")
    @PostMapping
    public ResultDTO<WebRoleDTO> create(@RequestBody @Valid final WebRoleDTO roleDTO) {
        final Role model = this.roleConverter.toModel(roleDTO);
        this.roleService.save(model, roleDTO.getResourceIds());
        if (log.isInfoEnabled()) {
            log.info("{} instance {} was created.", Role.class.getSimpleName(), model.getId());
        }
        return this.roleConverter.toResultDTO(model);
    }

    /**
     * 删除操作
     *
     * @param id 实体对象ID
     * @return 操作结果
     */
    @Timed
    @ApiOperation(value = "删除操作")
    @DeleteMapping(value = "/{id}")
    public ResultDTO<Void> delete(@PathVariable final UUID id) {
        this.roleService.delete(id);
        if (log.isInfoEnabled()) {
            log.info("{} instance {} was disable.", Role.class.getSimpleName(), id);
        }
        return ResultDTO.success();
    }

    /**
     * 锁定|解锁操作
     *
     * @param id 实体对象ID
     * @return 操作结果
     */
    @Timed
    @ApiOperation(value = "锁定|解锁操作")
    @PostMapping(value = "/lock/{id}")
    public ResultDTO<Void> lock(@PathVariable final UUID id) {
        this.roleService.lock(id);
        if (log.isInfoEnabled()) {
            log.info("{} instance {} was locked.", Role.class.getSimpleName(), id);
        }
        return ResultDTO.success();
    }

    /**
     * 更新操作
     *
     * @param id 实体对象ID
     * @param roleDTO 更新资源的DTO
     * @return 更新后资源
     */
    @Timed
    @ApiOperation(value = "更新操作")
    @PutMapping(value = "/{id}")
    public ResultDTO<WebRoleDTO> update(@PathVariable final UUID id, @RequestBody @Valid final WebRoleDTO roleDTO) {
        roleDTO.setId(id);
        final Role model = this.roleConverter.toModel(roleDTO);
        this.roleService.save(model, roleDTO.getResourceIds());
        if (log.isInfoEnabled()) {
            log.info("{} instance {} was updated.", Role.class.getSimpleName(), model.getId());
        }
        return this.roleConverter.toResultDTO(model);
    }



    /**
     * 获取分页数据
     *
     * @param pageable 分页+排序参数
     * @return 分页数据
     */
    @Timed
    @ApiOperation(value = "获取分页数据")
    @PostMapping(value = "/s")
    public PageResultDTO<WebRoleDTO> search(@PageableDefault(sort = {"code"}, direction = Sort.Direction.ASC) final Pageable pageable,
                                            @QuerydslPredicate(root = Role.class) Predicate predicate) {
        UserPrincipal currentUser = CurrentUserContextHolder.getCurrentUser();
        if (currentUser == null) {
            throw ExceptionHolder.serviceException(GlobalErrorCode.E2000000001);
        }
        if (currentUser.getProjectId() != null) {
            predicate = ExpressionUtils.and(predicate, QRole.role.controlRange.eq(ControlRange.PROJECT));
        } else if (currentUser.getTenantId() != null) {
            predicate = ExpressionUtils.and(predicate, QRole.role.controlRange.in(ControlRange.TENANT, ControlRange.PROJECT));
        }
        final Page<Role> models = this.roleRepository.findAll(predicate, pageable);
        return this.roleConverter.toResultDTO(models);
    }

    /**
     * 取得详细数据
     *
     * @param id 实体对象ID
     * @return 资源详细
     */
    @Timed
    @ApiOperation(value = "获取详细数据")
    @GetMapping(value = "/{id}")
    public ResultDTO<WebRoleDTO> get(@PathVariable final UUID id) {
        final Role model = this.roleRepository.findById(id)
                .orElseThrow(() -> ExceptionHolder.serviceException(UaaErrorCode.E2001005002, Role.class.getSimpleName()));
        return this.roleConverter.toResultDTOForView(model);
    }
}
